class cellular {
  gridArray = []
  pointArray = []
  rectWidth = 10
  constructor(gridArray, rectWidth) {
    this.gridArray = gridArray
    this.rectWidth = rectWidth
  }
  
  addPoint(x, y) {
    const gridPointIndex = this.findGridIndex({ x, y })
    const realPoint = [
      this.gridArray[gridPointIndex[0]][gridPointIndex[1]][0],
      this.gridArray[gridPointIndex[0]][gridPointIndex[1]][1]
    ]
    this.pointArray.push({
      x: realPoint[0] + this.rectWidth / 2,
      y: realPoint[1] + this.rectWidth / 2,
      row: gridPointIndex[0],
      column: gridPointIndex[1]
    })
    console.log(this.pointArray)
  }

  findGridIndex(point) {
    let hitPoint = []
    for (let i = 0; i < this.gridArray.length; i++) {
      let rows = this.gridArray[i]
      for (let j = 0; j < rows.length; j++) {
        const grid = rows[j]
        const boundingBox = [
          [grid[0], grid[1]],
          [grid[0] + this.rectWidth, grid[1] + this.rectWidth]
        ]
        if (
          point.x > boundingBox[0][0] &&
          point.y > boundingBox[0][1] &&
          point.x < boundingBox[1][0] &&
          point.y < boundingBox[1][1]
        ) {
          hitPoint.push(i, j)
        }
      }
    }
    return hitPoint
  }

  // 计算规则
  calcByRule() {
    this.gridArray.forEach((rowPoints, row) => {
      rowPoints.forEach((gridPoint, column) => {
        let roundPointNum = 0
        for (let j = 0; j < this.pointArray.length; j++) {
          const otherPoint = this.pointArray[j]
          if (
            (row === otherPoint.row - 1 && column === otherPoint.column - 1) ||
            (row === otherPoint.row - 1 && column === otherPoint.column) ||
            (row === otherPoint.row - 1 && column === otherPoint.column + 1) ||
            (row === otherPoint.row && column === otherPoint.column - 1) ||
            (row === otherPoint.row && column === otherPoint.column + 1) ||
            (row === otherPoint.row + 1 && column === otherPoint.column - 1) ||
            (row === otherPoint.row + 1 && column === otherPoint.column) ||
            (row === otherPoint.row + 1 && column === otherPoint.column + 1)
          ) {
            roundPointNum++
          }
        }
        const isFindInPointArray =
          this.pointArray.findIndex(
            otherP =>
              otherP.x === gridPoint[0] + this.rectWidth / 2 &&
              otherP.y === gridPoint[1] + this.rectWidth / 2
          ) > -1
        if (roundPointNum >= 4) {
          if (isFindInPointArray) {
            this.pointArray.splice(isFindInPointArray, 1)
          }
        } else if (roundPointNum === 3) {
          this.pointArray.push({
            x: gridPoint[0] + this.rectWidth / 2,
            y: gridPoint[1] + this.rectWidth / 2,
            row: row,
            column: column
          })
        }
      })
    })
  }
}

export default cellular